package com.orphan.marketFront.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Objects;

public class Base64ToStream {
    public static String ImageToBase64(String imgPath) {
        byte[] data = null;
        InputStream in = null;
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Base64.encodeBase64String(Objects.requireNonNull(data));
    }

    public static void Base64ToStream(String base64) {

        String fileType = "png";
        InputStream input = null;
        try {
            byte[] imageByte = Base64.decodeBase64(base64);
            input = new ByteArrayInputStream(imageByte);
            BufferedImage bi = ImageIO.read(input);
            File file = new File("d://Base64ToStream." + fileType + "");
            ImageIO.write(bi, "png", file);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}